package com.github.soiff.shadow.plugin.helper;

import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;
import org.joda.time.DateTime;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Soiff on 2016/05/20.
 *
 * @author : Soiff
 */
public class FormatDateHelper implements Helper {
    Map<String, SimpleDateFormat> sdfMap = new HashMap<String, SimpleDateFormat>();
    public FormatDateHelper () {
        sdfMap.put("gmt", new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy"));
        sdfMap.put("day", new SimpleDateFormat("yyyy-MM-dd"));
        sdfMap.put("default", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public CharSequence apply(Object dateObj, Options options) throws IOException {
        if(dateObj == null) {
            return "";
        } else {
            Date date = (new DateTime(dateObj)).toDate();
            String format = (String)options.param(0, "default");
            if(format.equals("ut")) {
                return Long.toString(date.getTime());
            } else {
                if(!this.sdfMap.containsKey(format)) {
                    this.sdfMap.put(format, new SimpleDateFormat(format));
                }

                return ((SimpleDateFormat)this.sdfMap.get(format)).format(date);
            }
        }
    }
}
